/*
 * Copyright 2012 Daniel Kurka
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.googlecode.mgwt.expenses.client.places;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;

public class ExpensePlace extends Place {

	public static final ExpensePlace DEFAULT_PLACE = new ExpensePlace("", false, false);

	private boolean detail;
	private boolean edit;
	private final String id;

	public ExpensePlace(String id, boolean detail, boolean edit) {
		this.id = id;
		this.detail = detail;
		this.edit = edit;

	}

	public static class Tokenizer implements PlaceTokenizer<ExpensePlace> {

		@Override
		public ExpensePlace getPlace(String token) {

			if (token == null || token.trim().equals("")) {
				return DEFAULT_PLACE;
			}

			String[] split = token.split(";");
			if (split.length != 3) {
				return DEFAULT_PLACE;
			}

			String id = split[0];
			boolean detail = split[1].equals("t");
			boolean edit = split[2].equals("t");

			return new ExpensePlace(id, detail, edit);

		}

		@Override
		public String getToken(ExpensePlace place) {
			StringBuffer buffer = new StringBuffer();

			if (place.getId() != null) {
				buffer.append(place.getId());
			}

			buffer.append(";");

			if (place.isDetail()) {
				buffer.append("t");
			} else {
				buffer.append("f");
			}
			buffer.append(";");

			if (place.isEdit()) {
				buffer.append("t");
			} else {
				buffer.append("f");
			}

			return buffer.toString();
		}
	}

	public boolean isDetail() {
		return detail;
	}

	public boolean isEdit() {
		return edit;
	}

	public String getId() {
		return id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (detail ? 1231 : 1237);
		result = prime * result + (edit ? 1231 : 1237);
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ExpensePlace other = (ExpensePlace) obj;
		if (detail != other.detail)
			return false;
		if (edit != other.edit)
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

}
